package com.gxp.wx.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.support.RequestContextUtils;

import com.gxp.pojo.WXOrder;
import com.gxp.service.OrderService;
import com.gxp.util.common.GXPConstant;
import com.gxp.wx.message.resp.TextMessage;
import com.gxp.wx.util.MessageUtil;

@Service
public class CoreServiceImpl implements CoreService {
	
	private Logger logger = Logger.getLogger(CoreServiceImpl.class);
	
	@Autowired
	private OrderService orderService;
	/**
	 * 
	 * @param request
	 * @return
	 */
	public String processRequest(HttpServletRequest request) {
		ApplicationContext ctx = RequestContextUtils.getWebApplicationContext(request);
		String notFoundError = ctx.getMessage("msg.wx.notfound", null, RequestContextUtils.getLocale(request));
		String helptips = ctx.getMessage("msg.wx.help.tips", null, RequestContextUtils.getLocale(request));
		logger.debug("processRequest from weixin ......");
		String respMessage = null;
		try {
			// Ĭ�Ϸ��ص��ı���Ϣ����
			String respContent = notFoundError + "\n" + helptips;

			// xml�������
			Map<String, String> requestMap = MessageUtil.parseXml(request);

			// ���ͷ��ʺţ�open_id��
			String fromUserName = requestMap.get("FromUserName");
			logger.debug("from user name: " + fromUserName);
			// �����ʺ�
			String toUserName = requestMap.get("ToUserName");
			logger.debug("to user name: " + toUserName);
			// ��Ϣ����
			String msgType = requestMap.get("MsgType");
			logger.debug("msgType: " + msgType);
			logger.debug("content : " + requestMap.get("Content"));
			
			// �ظ��ı���Ϣ
			TextMessage textMessage = new TextMessage();
			textMessage.setToUserName(fromUserName);
			textMessage.setFromUserName(toUserName);
			textMessage.setCreateTime(new Date().getTime());
			textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
			textMessage.setFuncFlag(0);

			// �ı���Ϣ
			if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
				String oriContent = requestMap.get("Content");
				String content  = oriContent.trim();
				String helpch = ctx.getMessage("msg.wx.help", null, RequestContextUtils.getLocale(request));
				String help1 = ctx.getMessage("msg.wx.help1", null, RequestContextUtils.getLocale(request));
				String help2 = ctx.getMessage("msg.wx.help2", null, RequestContextUtils.getLocale(request));
				String help3 = ctx.getMessage("msg.wx.help3", null, RequestContextUtils.getLocale(request));
				
				StringBuffer sb = new StringBuffer();
				sb.append(help1);
				sb.append("\n\n");
				sb.append(help2);
				sb.append("\n\n");
				sb.append("<a href=\"http://115.28.34.186/wx/gameIntro\">" + help3 + "</a>");
				
				if ("help".equalsIgnoreCase(content) || "?".equalsIgnoreCase(content) || helpch.equalsIgnoreCase(content)) {
					respContent = sb.toString();
				} else if (content != null && !"".equals(content)) {
					
					String regEx="[`~!@#$%^&*()=|{}':;',\\[\\].<>/?~��@#��%����&*��������|{}������������������������]";
			        Pattern p = Pattern.compile(regEx);      
			        Matcher m = p.matcher(content);      
			        content = m.replaceAll("").trim();
			        content.replace("insert", "");
			        content.replace("update", "");
			        content.replace("delete", "");
			        content.replace("drop", "");
			        content.replace("select", "");
			        content.replace("alter", "");
			        logger.debug("content after replace is : " + content);
					String[] keywords = content.split("\\+");
					logger.debug("keywords : " + keywords.length);
					List<WXOrder> result = null;
					if (keywords.length <= 1 || keywords.length > 3) {
						respContent = sb.toString();
					} else if (keywords.length == 2) {
						Map<String, Object> param = new HashMap<String, Object>();
						String gameKeywords = keywords[0].trim();
						String serverKeywords = keywords[1].trim();
						if ("".equals(gameKeywords) || "".equals(serverKeywords)) {
							respContent = sb.toString();
						} else {
							param.put(GXPConstant.MAPPER_KEY_GAME_KEYWORDS, gameKeywords);
							param.put(GXPConstant.MAPPER_KEY_SERVER_KEYWORDS, serverKeywords);
							result = orderService.findOrdersForWx(param);
						}
						
					} else if (keywords.length == 3) {
						String gameKeywords = keywords[0].trim();
						String serverKeywords = keywords[1].trim();
						String goodsKeywords = keywords[2].trim();
						if ("".equals(gameKeywords) || "".equals(serverKeywords) || "".equals(goodsKeywords)) {
							respContent = sb.toString();
						} else {
							Map<String, Object> param = new HashMap<String, Object>();
							param.put(GXPConstant.MAPPER_KEY_GAME_KEYWORDS, keywords[0]);
							param.put(GXPConstant.MAPPER_KEY_SERVER_KEYWORDS, keywords[1]);
							param.put(GXPConstant.MAPPER_KEY_GOODS_KEYWORDS, keywords[2]);	
							result = orderService.findOrdersForWx(param);
						}
						
					}
					if (result != null && !result.isEmpty()) {
						String tips = ctx.getMessage("msg.wx.order.tips", null, RequestContextUtils.getLocale(request));
						String priceunit = ctx.getMessage("Label.common.price.unit", null, RequestContextUtils.getLocale(request));
						
						
						
						StringBuffer resultSb = new StringBuffer();
						resultSb.append(tips);
						resultSb.append("\n");
						for(WXOrder order : result) {
							resultSb.append("\n");
							resultSb.append("<a href=\"http://115.28.34.186/wx/orderInfo/" + order.getOrderId() + "/" + order.getUserId() + "\">" + order.getOrg() + "</a>");
							resultSb.append(":");
							resultSb.append("\n");
							resultSb.append(order.getPrice());
							resultSb.append(priceunit);
							resultSb.append("/");
							resultSb.append(order.getUnit());
							resultSb.append("\n");
						}
						
						respContent = resultSb.toString();
					}
				}
//				respContent = "���͵����ı���Ϣ��";
			}
			// ͼƬ��Ϣ
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {
				respContent = "���͵���ͼƬ��Ϣ��";
			}
			// ����λ����Ϣ
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {
				respContent = "���͵��ǵ���λ����Ϣ��";
			}
			// ������Ϣ
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {
				respContent = "���͵���������Ϣ��";
			}
			// ��Ƶ��Ϣ
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {
				respContent = "���͵�����Ƶ��Ϣ��";
			}
			// �¼�����
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
				// �¼�����
				String eventType = requestMap.get("Event");
				// ����
				if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
					respContent = ctx.getMessage("msg.wx.subscribe", null, RequestContextUtils.getLocale(request)) + "\n" + helptips;
				}
				// ȡ����
				else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
					// TODO ȡ���ĺ��û����ղ������ںŷ��͵���Ϣ����˲���Ҫ�ظ���Ϣ
				}
				// �Զ���˵�����¼�
				else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {
					// TODO �Զ���˵�Ȩû�п��ţ��ݲ����������Ϣ
				}
			}

			textMessage.setContent(respContent);
			respMessage = MessageUtil.textMessageToXml(textMessage);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return respMessage;
	}
}
